// Put together municipality data similar to that used in Dancygier et al. 2015
//
// Last changed: 2020-03-18 (KOL)

  clear all
  use "D:\SCB_ConPol\Stata\RTB\Fodelseuppg.dta", clear
  bysort LopNr: egen cID = count(LopNr)
  keep if cID == 1
  
  keep LopNr UtlSvBakG FodArMan Kon
  tempfile fd 
  save `fd'
  
  use "E:\ProjData\UtplaceringsData8594\utp-LisaData.dta"
  
  merge m:1 LopNr using `fd', nogen keep(1 3) 
  
  gen kkod = floor(Forsamling/100)
  destring kkod, replace
  gen year = Ar 

  gen Vuxen = Ar-floor(FodArMan/100) > 17 if FodArMan <.
  
  merge m:1 kkod year using "E:\ProjData\UtplaceringsData8594\utp-KommunData91_10.dta", keepusing(Kvalresc FMpartytotc ///
  Kvalresfp FMpartytotfp Kvalreskd FMpartytotkd Kvalresm FMpartytotm Kvalresmp FMpartytotmp ///
  Kvalresovr FMpartytotovr Kvalress FMpartytots Kvalressd FMpartytotsd Kvalresv FMpartytotv ///
  FMpartytotovrsd Kvalresovrsd Fmtot dm gallagher sdrostkval nydrostkval listafinnsNyD listafinnsSD rostber effpar)

  gen Invandrad = UtlSvBakG == 11 if UtlSvBakG <.
  bysort kkod Ar: egen mUtb_infodda=mean(UtbAr) if Invandrad==0
  bysort kkod Ar: egen amUtb_infodda=min(mUtb_infodda)

  bysort kkod Ar: egen TotInv=total(Invandrad)
  bysort kkod IFAUkod Ar: egen cIFAUkod=count(IFAUkod) if Invandrad==1
  gen shareIFAUkod=cIFAUkod/TotInv
  sort kkod Ar IFAUkod
  bysort kkod Ar IFAUkod: gen occ2=_n
  bysort kkod Ar: egen aHerfindahl=total(shareIFAUkod^2) if occ2==1
  bysort kkod Ar: egen Herfindahl=min(aHerfindahl)
  drop aHerfindahl cIFAUkod TotInv occ2
  
 // Add "opportunity structure variables"  
  preserve
    use "E:\ProjData\WAIUIP\munivars_scb.dta", clear 
    rename municode kkod
    gen Ar = 2014
    tempfile pv
    save `pv'
  restore
  
  capture drop _merge
  merge m:1 kkod Ar using `pv' 
  
  replace effectiveparties = effpar if mi(effectiveparties)
  replace disproportionality = gallagher if mi(disproportionality)
  replace leftshare = (Kvalress + Kvalresv + Kvalresmp)/100 if mi(leftshare)
  bysort kkod Ar: egen amigrantshare = mean(Invandrad) if Vuxen == 1
  bysort kkod Ar: egen migrantshare = max(amigrantshare)  
  
  keep kkod Ar mUtb_infodda Herfindahl effectiveparties disproportionality leftshare listafinnsSD sdrostkval nydrostkval listafinnsNyD migrantshare
  compress
  bysort kkod Ar: gen occ = _n
  keep if occ == 1
  drop if Ar == 1990
  drop occ
  save "E:\ProjData\UtplaceringsData8594\utp-MunData.dta", replace
